#include "insert.h"
#include <fstream>
#include<iostream>
using namespace std;
int ins_data(tmysql tmy){
		//printf("mysql client version:%s\n",mysql_get_client_info());
		MYSQL *con=mysql_init(NULL);
		//MYSQL_RES *res_ptr;
		//MYSQL_ROW sqlrow;
		//MYSQL_FIELD *fd;
		//cout<<"insert begine"<<endl;
		int res,i,j;
		int msTimeout=5;
		char ctem[2],chum[2],cinfr[1],clig[1],cfir[1];
		sprintf(ctem,"%d",tmy.tem);
		sprintf(chum,"%d",tmy.humi);
		sprintf(cinfr,"%d",tmy.infr);
		sprintf(clig,"%d",tmy.light);
		sprintf(cfir,"%d",tmy.fire);
		string stem(ctem);
		string shum(chum);
		string sinfr(cinfr);
		string sligh(clig);
		string sfir(cfir);

		mysql_options(con,MYSQL_OPT_CONNECT_TIMEOUT,(const char*)&msTimeout);

		if(con==NULL)
		{
				fprintf(stderr,"%s\n",mysql_error(con));
				printf("init connect fail\n");
		}
		con=mysql_real_connect(con,host,"gnu","campus123","campus",0,NULL,0);
		if(!con)
		{
				//				fprintf(stderr, "%s\n", mysql_error(con));
				printf("connect fail\n");
				cout<<host<<endl;
				ofstream fout("/home/pi/localdb.txt",ios::out|ios::app);
				string str=stem+"\t"+shum+"\t"+sfir+"\t"+sligh+"\t"+sinfr+"\t"+"0\t"+tmy.stime;
				fout<<str<<endl;
				fout.close();
		}
		else
		{
				string sinf;
				sinf="insert into sensors values(null,"+stem+","+shum+","+sfir+","+sligh+","+sinfr+",0,"+tmy.stime+")";
				if(con) {
						res=mysql_query(con,sinf.c_str());
						ofstream fout("/home/pi/localdb.txt",ios::out|ios::app);
						string str=stem+"\t"+shum+"\t"+sfir+"\t"+sligh+"\t"+sinfr+"\t"+"0\t"+tmy.stime;
						fout<<str<<endl;
						fout.close();

						if(res)
								printf("insert error:%s\n",mysql_error(con));
						/*
						   else
						   {
						   res_ptr=mysql_store_result(con);
						   if(res_ptr)
						   {
						   printf("%lu Rows\n",(unsigned long)mysql_num_rows(res_ptr));
						   j= mysql_num_fields(res_ptr);
						   while((sqlrow = mysql_fetch_row(res_ptr)))
						   {
						   for(i=0;i<j;i++)
						   printf("%s\t", sqlrow[i]);
						   printf("\n");
						   }//while
						   if(mysql_errno(con))
						//fprintf(stderr,"Retrive error:s\n",mysql_error(con));
						;
						}//if
						mysql_free_result(res_ptr);
						}//else
						 */
				}//if
				else
						printf("Connection failed\n");
		}
		mysql_close(con);
		//cout<<"insert ok"<<endl;
		return 0;
}
